#pragma once
#include "log.hpp"
#include <iostream>
#include <string>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>
#define N 1024

using namespace std;
// using func_t=function<string(const string&)>;
typedef function<string(const string &, const string &, const uint16_t &)> func_t;

extern Log log;
enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};
string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;
class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport, const string &ip = defaultip)
        : _sockfd(0), _port(port), _ip(ip), _isrunning(false)
    {
    }
    void Init()
    {
        // 1.创建udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            log(Fatal, "socket create error, sockfd: %d", _sockfd);
            exit(SOCKET_ERR);
        }
        log(Info, "socket create successfully, socket: %d", _sockfd);

        // 2.绑定端口
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); // 必须保证端口号是网络自介序列，因为端口号是要发送给对方的
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // local.sin_addr.s_addr = INADDR_ANY;

        int ret = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (ret != 0)
        {
            log(Fatal, "socket bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        log(Info, "socket bind successfully, errno: %d, err string: %s", errno, strerror(errno));
    }
    void checkUser(const struct sockaddr_in &client, const string &clientIP, const uint16_t &clientPort)
    {
        auto it = _onlineuser.find(clientIP);
        if (it == _onlineuser.end())
        {
            _onlineuser.insert({clientIP, client});
            cout << "[" << clientIP << ":" << clientPort << "] add to online user." << endl;
        }
    }
    void Broadcast(const string &info, const string &clientIP, const uint16_t &clientPort)
    {
        for (auto &user : _onlineuser)
        {
            // 充当了一次数据的处理
            string msg = "[" + clientIP + ":" + to_string(clientPort) + "]#" + info;

            // 发送数据：处理后的回声数据发送回原客户端
            socklen_t len = sizeof(user.second);
            sendto(_sockfd, msg.c_str(), msg.size(), 0, (const struct sockaddr *)&(user.second), len);
        }
    }
    void Run(func_t func)
    {
        _isrunning = true;
        char inbuffer[N];

        // 无限循环使服务器持续工作
        // 实现 UDP 回声服务器功能：接收客户端数据，添加特定前缀后原样返回给客户端。
        // 代码通过recvfrom和sendto两个UDP核心接口完成数据的接收和发送，实现了基本的无连接通信模式。
        while (true)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            // 接收客户端发送的数据：成功接收则返回实际接收的字节数n，接收失败则记录警告日志并继续下一次循环
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                log(Warning, "recvfrom error, error: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            uint16_t clientPort = ntohs(client.sin_port);
            string clientIP = inet_ntoa(client.sin_addr);

            checkUser(client, clientIP, clientPort);
            string info = inbuffer;
            Broadcast(info, clientIP, clientPort);
        }
    }
    ~UdpServer()
    {
        if (_sockfd > 0)
        {
            close(_sockfd);
        }
    }

private:
    int _sockfd;    // 网络文件描述符
    string _ip;     // 任意地址绑定
    uint16_t _port; // 表面服务器状况
    bool _isrunning;
    unordered_map<string, struct sockaddr_in> _onlineuser; // 在线用户列表
};
